<?php

namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Address extends Model
{

    protected $table = 'address';
    protected $fillable = ['address_name', 'pid', 'level'];

    // 获取子级地址
    public function children()
    {
        return $this->hasMany(Address::class, 'pid', 'id');
    }

    // 获取父级地址
    public function parent()
    {
        return $this->belongsTo(Address::class, 'pid', 'id');
    }

    // 获取所有子级地址（递归）
    public function getChildrenRecursive()
    {
        return $this->children()->with('childrenRecursive')->get();
    }

    // 关联方法：获取省份（level=1）
    public static function getProvinces()
    {
        return self::where('level', 1)->get();
    }

    // 关联方法：获取城市（level=2）
    public function cities()
    {
        return $this->children()->where('level', 2);
    }

    // 关联方法：获取区县（level=3）
    public function districts()
    {
        return $this->children()->where('level', 3);
    }
}
